package com.itic.appbase.applications.files.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.openoffice.OfficeToSwf;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.StringHelper;
/**
 * 
 * @author: djp_ivan
 * @date: 2015年4月14日 下午3:32:32
 * @version: V1.0  
 * @Update_Comments: by djp_ivan at 2015年4月14日 - description
 */
@Controller
@RequestMapping(value="/fileDownload")
public class FileDownloadController extends BaseController{
    
    /**
     * 文件下载
     * @param filePath
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/download")
    public String download(String filePath,HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            if(StringHelper.isNotBlank(filePath)){//路径是否为空
                String path = FileHelper.getRootDir()+filePath;
                File file = new File(path);
                String fileName = file.getName();//文件名称
                fileName = toUtf8String(request, fileName.replace(" ", ""));
                response.reset();// 清空response
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                        
                inputStream = new BufferedInputStream(new FileInputStream(file));
                outputStream = new BufferedOutputStream(response.getOutputStream());
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
            }else{
                LOGGER.info("FileUploadController|download(文件下载)路径(filePath)不能为空");
                return ResponseCode.PARAM_INVALID.getCode();
            }
        }catch(Exception e) {
            LOGGER.info("FileUploadController|download(文件下载)出错",e);
            throw new RuntimeException(e);
        }finally{
            if(inputStream!=null){
                inputStream.close();
            }
            if(outputStream!=null){
                outputStream.flush();
                outputStream.close();
            }
        }
        return null;
    }
    
    /**
     * 文件名代码转换
     * IE的话，通过URLEncoder对filename进行UTF8编码。
     * 而其他的浏览器（firefox、chrome、safari、opera），则通过字节转换成ISO8859-1
     * @param request
     * @param filename
     * @return String
     */
    private  String toUtf8String (HttpServletRequest request,String filename){
        String  newName = filename;
        String agent = request.getHeader("User-Agent"); //获取浏览器类型
        try {
            if (agent != null && agent.indexOf("MSIE") != -1) {
                newName = URLEncoder.encode(newName.toString(), "UTF-8");
            } else {
                newName = new String(newName.getBytes("UTF-8"), "ISO8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.info("UploadFile|toUtf8String：转换异常", e);
        }
        return newName;
    }
    
    
    /**
     * 读取图到前台
     * @param os
     * @param filePath
     * @throws IOException
     */
    @RequestMapping("/getImage")
    public void getImage(OutputStream os,String filePath) throws IOException{
        if (StringUtils.isNotBlank(filePath)){
            File file = new File(FileHelper.getRootDir() + filePath);
            if (file.exists()){
                InputStream inputStream = null;
                inputStream = new BufferedInputStream(new FileInputStream(file));
                FileCopyUtils.copy(inputStream,os);
                os.flush();
                os.close();
                inputStream.close();
            }
        }
    }
    
    /**
     * 文档预览 
     * @param request
     * @param response
     * @throws IOException 
     * @throws Exception
     */
    @RequestMapping("/showOffice")
    public void showOfficeFile(OutputStream os,String filePath) throws IOException {
        if (StringUtils.isNotBlank(filePath)){
            filePath = FileHelper.getRootDir() + filePath;
            String swfFilePath = filePath.substring(0, filePath.lastIndexOf(".")) + ".swf";
            File f = new File(swfFilePath);
            boolean hasFile = true;
            if (!f.exists()) {
                LOGGER.info("未生成过swf文件，即将生成的SWF文件，路径为: " + swfFilePath);
                hasFile = OfficeToSwf.toSwf(filePath);
            }
            LOGGER.info("SWF文件已生成，路径为: " + swfFilePath);
            if ( hasFile ){
                InputStream inputStream = null;
                inputStream = new BufferedInputStream(new FileInputStream(f));
                FileCopyUtils.copy(inputStream,os);
                os.flush();
                os.close();
                inputStream.close();
            }
        }
    }
    
    /**
     * 文档预览页面
     * @return
     */
    @RequestMapping(value = "/initShowOffice")
    public String initShowOffice(@ModelAttribute String filePath) {
        return "/common/documentView";
    }
}
